<?php
/**
 * 明源管理后台的用户认证
 *
 * Created by PhpStorm.
 * User: wangx08
 * Date: 2015-03-28
 * Time: 18:24
 */

namespace mybackend\models;

use common\support\CacheManage;
use yii\web\IdentityInterface;
use common\services\myhtsq\ErpInterfaceService;

class MyAdminIdentity implements IdentityInterface {

    public $userguid;    
    public $usercode;
    public $username;
    public $isAdmin;

    /**
     * @param $entity
     * @return MyAdminIdentity|null
     */
    private static function convertModel($entity)
    {
        if (!isset($entity))
        {
            return null;
        }

        $user = new MyAdminIdentity();
        $user->usercode = $entity->UserCode;
        $user->username = $entity->UserName;
        $user->userguid = $entity->UserGUID;
        $user->isAdmin = $entity->IsAdmin == 1;
        return $user;
    }

    /**
     * $userCode的格式为：usercode
     *
     * Finds an identity by the given ID.
     * @param string|integer $userCode the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($userCode)
    {
        $sessionId = \Yii::$app->session->getId();
        $user = CacheManage::getUserIdentityCache($sessionId);
        if(is_null($user) || $user === false) {
            $userEntity = ErpInterfaceService::getUserByCode($userCode);
            $user = self::convertModel($userEntity);
            if(is_null($user)) {
                return $user;                       
            }
            CacheManage::setUserIdentityCache($sessionId,$user);
        }
        \Yii::$app->user->on(\yii\web\User::EVENT_AFTER_LOGOUT,['mybackend\models\MyAdminIdentity','afterLogout']);
        return $user;
    }

    public static function clearCache($userCode){
        $sessionId = \Yii::$app->session->getId();
        CacheManage::deleteUserIdentityCache($sessionId);
    }

    public static function afterLogout($event){
        $sessionId = \Yii::$app->session->getId();
        CacheManage::deleteUserIdentityCache($sessionId);
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $user = self::findIdentity($token);
        return $user;
    }


    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|integer an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        return $this->usercode;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        return $this->usercode;
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return boolean whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return $authKey === $this->usercode;
    }
}